package com.dwsoft.word;

import com.dwsoft.pojo.DataKpiDO;
import com.dwsoft.utils.Regexs;
import com.dwsoft.xml.XParagraph;
import com.dwsoft.xml.XParagraphPiece;
import org.springframework.stereotype.Component;
import word.api.interfaces.IElement;
import word.w2004.Document2004;
import word.w2004.elements.Paragraph;
import word.w2004.elements.ParagraphPiece;
import word.w2004.style.Font;
import word.w2004.style.ParagraphPieceStyle;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sqw
 * @version 1.0
 * @description TODO
 * @ClassName TextStrategy
 * @Date 2020/8/5
 * @since jdk1.8
 */
@Component("paragraph")
public class WParagraph extends WElement<XParagraph> {

    @Override
    public void instance(XParagraph xmlNode, Document2004 document) throws NoSuchMethodException {
        List<XParagraphPiece> childrens = xmlNode.getXmlNodes();
        List<ParagraphPiece> wordPieces=new ArrayList<ParagraphPiece>();
        for(XParagraphPiece piece : childrens){
            replaceParam(piece);
            ParagraphPieceStyle paragraphPieceStyle = ParagraphPiece.with(piece.getText()).withStyle();
            paragraphPieceStyle.fontSize(piece.getFontSize()).font(Font.SIMSUN).textColor(piece.getColor());
            if(piece.isBold()){
                paragraphPieceStyle.bold();
            }
            if(piece.isItalic()){
                paragraphPieceStyle.italic();
            }
            ParagraphPiece paragraphPiece = paragraphPieceStyle.create();
            wordPieces.add(paragraphPiece);
        }
        ParagraphPiece[] paragraphPieces= wordPieces.toArray(new ParagraphPiece[wordPieces.size()]);
        IElement paragraph = Paragraph.withPieces(paragraphPieces).withFirstIndent(xmlNode.isFirstIndent()).withStyle().create();
        document.addEle(paragraph);
    }

    protected void replaceParam(XParagraphPiece obj){
        String kpi=obj.getText();
        String param=searcheKpiParam(kpi);
        String[] paramArr=param.replace("${","").replace("}","").split("\\.");
        String kpiSn=paramArr[0];
        if(!kpiSn.equals("")){
            DataKpiDO kpiDO = dataKpiMapper.getKpi(kpiSn);
            String script=kpiDO.getKpiScript();
            if(params!=null){
                script= Regexs.whereSql(params,kpiDO.getKpiScript());
            }
            String value = dataKpiMapper.getKpiValueForText(script);
            String newValue= kpi.replaceAll("\\$\\{"+kpiSn+"\\}",value);
            obj.setText(newValue);
        }
    }
}
